import { App, Button, Flex, Form } from 'antd';
import { useCatch, useSpecialLayoutStyle } from '@/hooks';
import Map from '@/pages/historyReplay/components/Map.tsx';
import SearchForm, { FormData } from '@/pages/historyReplay/components/SearchForm.tsx';
import { useEffect, useMemo, useState } from 'react';
import TableWrapper from '@/pages/historyReplay/components/TableWrapper.tsx';
import { keepPreviousData, useQuery } from '@tanstack/react-query';
import HistoryReplayServices from '@/api/services/historyReplayServices.ts';
import SummaryWindow from '@/pages/historyReplay/components/SummaryWindow.tsx';
import { DescriptionsItemType } from 'antd/es/descriptions';
import dayjs from 'dayjs';
import { useSetLocationData } from '@/store/locationStore.ts';

const HistoryReplay = () => {
  const { message } = App.useApp();
  const { styles } = useSpecialLayoutStyle();
  const [form] = Form.useForm();
  const catchFn = useCatch();

  const [formData, setFormData] = useState<FormData>();
  const setLocationData = useSetLocationData();

  const { data, isFetching } = useQuery({
    placeholderData: keepPreviousData,
    queryKey: ['location', formData],
    queryFn: () =>
      catchFn(async () => {
        const { data } = await HistoryReplayServices.getLocationList({
          plateNumber: formData!.plateNumber,
          startTime: formData!.startTime.format('YYYY-MM-DD HH:mm:ss'),
          endTime: formData!.endTime.format('YYYY-MM-DD HH:mm:ss'),
          space: formData!.space,
          duration: formData!.duration,
        });
        if (data.length === 0) {
          message.info('该时段没有定位数据');
        }

        return data;
      }),
    // select: ({ data }) => data,
    enabled: !!formData,
    staleTime: 0,
  });

  useEffect(() => {
    if (data && data.length > 0) setLocationData(data);
  }, [data]);

  const { data: parkingData } = useQuery({
    placeholderData: keepPreviousData,
    queryKey: ['parkingLocationList', formData],
    queryFn: () =>
      catchFn(() =>
        HistoryReplayServices.getParkingLocationList({
          plateNumber: formData!.plateNumber,
          startTime: formData!.startTime.format('YYYY-MM-DD HH:mm:ss'),
          endTime: formData!.endTime.format('YYYY-MM-DD HH:mm:ss'),
          space: formData!.space,
          duration: formData!.duration,
        }),
      ),
    select: ({ data }) => data,
    enabled: !!formData,
    staleTime: 6000,
    gcTime: 6000,
  });

  const { data: list } = useQuery({
    placeholderData: keepPreviousData,
    queryKey: ['alarmList', formData],
    queryFn: () =>
      catchFn(() =>
        HistoryReplayServices.getAlarmList({
          plateNumber: formData!.plateNumber,
          startTime: formData!.startTime.format('YYYY-MM-DD HH:mm:ss'),
          endTime: formData!.endTime.format('YYYY-MM-DD HH:mm:ss'),
          page: 1,
          limit: 1,
          order: 'id DESC',
        }),
      ),
    select: ({ data, total }) => ({ data, total }),
    enabled: !!formData,
    staleTime: 0,
  });

  const getDate = (s: number) => {
    const hours = Math.floor(s / 3600); // 将秒数转为小时
    const minutes = Math.floor((s % 3600) / 60); // 计算剩余的分钟
    const seconds = s % 60; // 计算剩余的秒数

    if (hours && minutes && seconds) {
      return `${hours}小时${minutes}分钟${seconds}秒`;
    } else if (minutes && seconds) {
      return `${minutes}分钟${seconds}秒`;
    } else if (seconds) {
      return `${seconds}秒`;
    }
  };

  const items = useMemo<DescriptionsItemType[]>(() => {
    if (!(parkingData && parkingData.length > 0) || !(data && data.length > 0)) {
      return [];
    }

    const endTime = data?.[data.length - 1]?.deviceTime;
    const startTime = data?.[0]?.deviceTime;
    const diffInSeconds = dayjs(endTime).diff(dayjs(startTime), 'second'); // 计算总的秒数差

    //计算parkingData的停车时长
    const parkingDuring = parkingData[0]?.parkDuration;

    return [
      { key: 'startAddress', label: '开始位置', children: data?.[0]?.address, span: 24 },
      {
        key: 'startAddress',
        label: '结束位置',
        children: data?.[data.length - 1]?.address,
        span: 24,
      },
      { key: 'startTime', label: '开始时间', children: startTime, span: 24 },
      { key: 'endTime', label: '结束时间', children: endTime, span: 24 },
      {
        key: 'totalDuring',
        label: '时长',
        children: getDate(diffInSeconds),
        span: 24,
      },
      {
        key: 'driveDuring',
        label: '驾驶时长',
        children: getDate(diffInSeconds - parkingDuring),
        span: 24,
      },
      { key: 'parkingDuring', label: '停车时长', children: getDate(parkingDuring), span: 24 },
      { key: 'locationCount', label: '总定位数量', children: parkingData.length, span: 24 },
      { key: 'alarmCount', label: '报警总数', children: list?.total, span: 24 },
    ];
  }, [parkingData, data, list]);

  return (
    <div className={`relative h-full`}>
      <Flex
        vertical
        className={`absolute left-0 top-0 h-full overflow-hidden rounded-2xl border-r backdrop-blur ${styles.leftWrapper}`}
      >
        <div className={`${styles.breakCrumb} px-10 pb-4 pt-8`}>历史回放</div>
        <Flex vertical className="h-full overflow-y-scroll px-6 py-8" justify="space-between">
          <SearchForm form={form} />
          <Button
            type="primary"
            block
            onClick={async () => {
              await form.validateFields();
              const formData = form.getFieldsValue();
              const fillAll = Object.entries(formData).every(([key, value]) => {
                return key === 'autoPlay' || value != undefined;
              });

              if (!fillAll) {
                message.error('请完成搜索项');
                return;
              }

              setFormData(formData);
            }}
          >
            搜索
          </Button>
        </Flex>
      </Flex>
      <Map loading={isFetching} carNo={formData?.plateNumber} />
      {data && data.length > 0 && <TableWrapper searchParams={formData} loading={isFetching} />}
      {items.length > 0 && <SummaryWindow items={items} />}
    </div>
  );
};

export default HistoryReplay;
